package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.util.FastDFSClient;
import com.changgou.file.util.FastDFSFile;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/file")
public class FileController {
    @PostMapping("/upload")
    public Result uploadFile(MultipartFile file) {
        try {
            if (file == null) {
                throw new RuntimeException("文件不存在");
            }
            String originalFilename = file.getOriginalFilename();
            if (StringUtils.isEmpty(originalFilename)) {
                throw new RuntimeException("文件名为空");
            }
            byte[] fileBytes = file.getBytes();
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, fileBytes, extName);
            String[] upload = FastDFSClient.upload(fastDFSFile);
            for (String s : upload) {
                System.out.println(s);
            }
            String url=FastDFSClient.getTrackerUrl()+upload[0]+"/"+upload[1];
            return new Result(true, StatusCode.OK, "文件上传成功",url);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, StatusCode.ERROR, "文件上传失败");
    }
//    @DeleteMapping("/delete/{url}")
//    public Result deleteFile(@PathVariable("url")String url){
//        try {
//            System.out.println(url);
//            FastDFSClient.deleteFile("group1","M00/00/00/wKjIgF5NI1CAFCU7AACAvfcBF3c382.jpg" );
//            return new Result(true, StatusCode.OK, "删除成功" );
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return new Result(false, StatusCode.ERROR, "删除失败" );
//    }
}
